package P100_realTypeOfArrayMustBeSubtypeOfGeneric;

import org.junit.Test;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * Desc:&emsp;&ensp;数组的真实类型必须是泛型的子类型
 *
 * @author 李渊&emsp;liyuan7@yusys.com.cn
 * @version 1.0
 * 
 */
public class demo {
    @Test
    public  void test1() {
        List<String> list = Arrays.asList("A", "B");
        String[] strings = list.toArray(new String[1]);
        for (String s:strings) {
            System.out.println(s);
        }

        System.out.println("--------------------");
        // list.toArray的方法不能满足需要
        // 抛出出异常是在这里，而不是在toArray中
        for (String s : toArray(list,String.class)) {
            System.out.println(s);
        }
    }

    public static final <T> T[] toArray(List<T> list) {
        T[] t = (T[]) new Object[list.size()];
        for (int i = 0; i < list.size(); i++) {
            t[i] = list.get(i);
        }
        return t;
    }

    @Test
    public void test2() {
        List<String> list = Arrays.asList("A", "B");
        for (String s : toArray(list,String.class)) {
            System.out.println(s);
        }
    }

    public static final <T> T[] toArray(List<T> list, Class<T> tClass) {
        T[] t = (T[]) Array.newInstance(tClass,list.size());
        for (int i = 0; i < list.size(); i++) {
            t[i] = list.get(i);
        }
        return t;
    }

    // 泛型集合转换为泛型数组时，泛型数组的真实类型不能是泛型类型的父类（如Object），只能是子类或自身类型
}
